package com.meatball.authorization.config

import com.meatball.authorization.data.entity.RoleEntity
import com.meatball.authorization.data.entity.UserEntity
import com.meatball.authorization.enum.RoleEnum
import com.meatball.authorization.repository.RoleRepository
import com.meatball.authorization.repository.UserRepository
import jakarta.annotation.PostConstruct
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Component

@Component
class PreSecurityInitializer (
    private val userRepository: UserRepository,
    private val roleRepository: RoleRepository,
    private val passwordEncoder: PasswordEncoder
) {
    @PostConstruct
    fun init() {
        // 角色
        val role = roleRepository.findByName(RoleEnum.ADMIN.value) ?: initializeRole()
        // 用户
        userRepository.findByUsername("meatball") ?: initializeUser(role)
    }

    /**
     * TODO 初始化角色
     *
     * @return
     */
    fun initializeRole(): RoleEntity {
        // 添加role
        val role = RoleEntity(
            name = "ROLE_ADMIN",
            description = "超级管理员"
        )
        // 保存角色
        return roleRepository.save(role)
    }

    /**
     * TODO 初始化超级管理员
     *
     * @param role 角色
     *
     * @author 张翔宇
     * @since 2024年3月23日
     */
    fun initializeUser(role: RoleEntity) {
        // 初始化用户
        val user = UserEntity(
            username = "meatball",
            password = passwordEncoder.encode("3238cd41307062a8256c427ac9723baa"),
            avatar = "https://meatball.org.cn:8000/images/2024/03/07/v2-3441507db209572e47109f8ca3f534de_r.jpg",
            nickname = "超级管理员",
            realName = "超级管理员",
            roles = mutableSetOf(role)
        )
        // 保存用户信息
        userRepository.save(user)
    }
}